package com.example.bookmall.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bookmall.entity.Result;
import com.example.bookmall.entity.usercore.User;
import com.example.bookmall.entity.usercore.UserDto;
import com.example.bookmall.mapper.UserMapper;
import com.example.bookmall.service.AdminUserService;
import com.example.bookmall.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.regex.Pattern;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;
    /*
    * 管理员删除用户
    * */
    @Override
    public Result deleteUser(Integer userId) {

        User user = userMapper.selectById(userId);

        if(user == null){
            return Result.error("用户不存在");
        }
        if(user.getRole()==2){
            return Result.error("不可以删除管理员");
        }

        user.setDeleted(1);


        int i  = userMapper.updateById(user);
        if(i>0){
            return Result.success();
        }
        return Result.error("删除失败");

    }

    /*
    * 管理员修改用户信息
    * */
    @Override
    public Result modifyUser(Integer userId, String username, String email, String phone, Integer status,Integer gender) {

        //TODO: 用户修改要加上性别
        User user = userMapper.selectById(userId);
        if(user == null){
            return Result.error("用户不存在");
        }
        user.setUsername(username);

        //TODO：这里也要允许之前没有的可以有没有

        if(!email.equals(user.getEmail())){
            User user1 = userService.selectByEmail(email);
            if(user1!=null){
                return Result.error("邮箱已被注册用户使用");
            }
            user.setEmail(email);
        }
        if(!phone.equals(user.getPhone())){
            User user1 = userService.selectByPhone(phone);
            if(user1!=null){
                return Result.error("手机号已被注册用户使用");
            }
            user.setPhone(phone);
        }



        user.setStatus(status);
        user.setGender(gender);
        userMapper.updateById(user);

        return Result.success();
    }


    @Override
    public Result addUser(UserDto userDto) {
        // 非空校验
        if (userDto.getUsername() == null || userDto.getUsername().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (userDto.getEmail() == null || userDto.getEmail().isEmpty()) {
            return Result.error("邮箱不能为空");
        }
        if (userDto.getPhone() == null || userDto.getPhone().isEmpty()) {
            return Result.error("手机号不能为空");
        }

        if (userDto.getStatus() == null) {
            return Result.error("状态不能为空");
        }

        // 格式校验
        if (!isValidEmail(userDto.getEmail())) {
            return Result.error("邮箱格式不正确");
        }
        if (!isValidPhone(userDto.getPhone())) {
            return Result.error("手机号格式不正确");
        }

        User user1 = userService.selectByEmail(userDto.getEmail());
        if (user1!=null){
            return Result.error("该邮箱已被注册");
        }
        User user2 = userService.selectByPhone(userDto.getPhone());
        if (user2!=null) {
            return Result.error("该手机号已被注册");
        }

        try {
            User addUser=new User();

            BeanUtils.copyProperties(userDto,addUser);
            // 密码加密处理
            String mPassword = MD5.create().digestHex("123456");
            addUser.setPassword(mPassword);
            addUser.setStatus(1);
            addUser.setRole(1);
            addUser.setCreateTime(LocalDateTime.now());

            // 插入用户数据
            if (userMapper.insert(addUser) > 0) {
                return Result.success();
            }
            return Result.error("添加失败，请稍后重试");
        } catch (Exception e) {

            return Result.error("添加失败，服务器内部错误");
        }
    }

    public Result findUser(String username, String email, String phone, Integer status) {
        // 创建条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 邮箱格式校验
        if (email != null && !email.isEmpty()) {
            if (!isValidEmail(email)) {
                return Result.error("邮箱格式不正确");
            }
            queryWrapper.like("email", email);
        }

        // 手机号格式校验
        if (phone != null && !phone.isEmpty()) {
            if (!isValidPhone(phone)) {
                return Result.error("手机号格式不正确");
            }
            queryWrapper.like("phone", phone);
        }

        // 处理用户名条件
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }

        // 处理状态条件
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        try {
            // 执行数据库查询
            List<User> users = userMapper.selectList(queryWrapper);

            // 返回成功结果
            return Result.success(users);
        } catch (Exception e) {

            // 返回错误结果
            return Result.error("查询失败，请稍后重试");
        }
    }

    //管理员模糊手机号查询
    @Override
    public Result findByPhone(String phone) {
        // 创建条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 手机号格式校验
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }

        // 查询所有匹配的用户列表
        List<User> userList = userMapper.selectList(queryWrapper);

        return Result.success(userList);
    }
    // 管理员模糊用户名查询
    @Override
    public Result findByUserName(String username) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 用户名格式校验
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }

        // 查询所有匹配的用户列表
        List<User> userList = userMapper.selectList(queryWrapper);

        return Result.success(userList);
    }

    // 管理员模糊邮箱查询
    @Override
    public Result findByEmail(String email) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 邮箱格式校验
        if (email != null && !email.isEmpty()) {
            queryWrapper.like("email", email);
        }

        // 查询所有匹配的用户列表
        List<User> userList = userMapper.selectList(queryWrapper);

        return Result.success(userList);
    }

    // 邮箱格式校验正则表达式
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"
    );

    // 手机号格式校验正则表达式（中国大陆）
    private static final Pattern PHONE_PATTERN = Pattern.compile(
            "^1[3-9]\\d{9}$"
    );

    // 邮箱格式校验方法
    private boolean isValidEmail(String email) {
        return !StringUtils.isEmpty(email) && EMAIL_PATTERN.matcher(email).matches();
    }

    // 手机号格式校验方法
    private boolean isValidPhone(String phone) {
        return !StringUtils.isEmpty(phone) && PHONE_PATTERN.matcher(phone).matches();
    }
}
